package com.vstudy.zx.interceptor;

import com.vstudy.zx.utils.ParamsUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

public class TeacherLoginInterceptor implements HandlerInterceptor {
    private static final String[] IGNORE_URL = {"/login"};

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        HttpSession session = request.getSession();
        Object user = session.getAttribute("teacher");
        if (user != null) {
            return true;
        }
        String servletPath = request.getServletPath();
        for (String s :
                IGNORE_URL) {
            if (servletPath.contains(s)) {
                return true;
            }
        }
        session.setAttribute("preUrl", servletPath);

        Map<String, String> params = ParamsUtil.queryStringToMap(request.getQueryString());
        session.setAttribute("params", params);

        request.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(request, response);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
